package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    //每分钟执行一次查看是否有超时未支付的订单
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理超时订单");
        //首先查看都有哪些订单是超时未支付
        List<Orders> ordersList = orderService.getOrdersTimeOut(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
                log.info("订单{}超时取消", orders.getId());
            }
        }
    }

    //凌晨一点的时候检测是否有订单未完成，如果有，则进行默认完成订单
    @Scheduled(cron = "0 0 1 * * ?")
    public void completeOrderDaily(){
        log.info("开始进行夜晚检查定时任务，检测是否有订单未完成");
        //获取所有未完成订单并且点单时间在00:00之前，状态为配送中的订单
        List<Orders> ordersList = orderMapper.listByTimeOut(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if (ordersList != null && !ordersList.isEmpty()){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(orders);
                //统一处理防止用户已经收到而忘记完成订单
                log.info("订单统一处理{}完成", orders.getId());
            }
        }
    }
}
